<?php

namespace app\recode\controller;

use \app\check\controller\Check;
use app\common\controller\Avatar;
use app\common\lib\Util;
use think\Db;

// 星盘档案管理控制器
class Cat extends Check
{
    /**
     * 添加档案袋
     */
    public function add()
    {
        $catname = input('name/s', '', 'htmlspecialchars');
        $avatar = input('avatar/s', '', 'htmlspecialchars');

        if (!$avatar) $avatar = 'uploads/recodecat/' . rand(1, 12) . '.png';// 默认档案袋图片随机  1-4

        $time = time();
        $uid = $this->user['id'];
        $data = [
            'name' => $catname,
            'avatar' => $avatar,
            'status' => 0,
            'create_time' => $time,
            'last_time' => $time,
            'uid' => $uid,
        ];
        $validate = validate('RecodeCat');

        if (!$validate->scene('add')->check($data))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $already = Db::table('app_cat')->where(['name' => $catname, 'uid' => $uid])->find();
        if (!empty($already))
        {
            return json(['code' => 10503, 'msg' => 'This cat name already exist.']);
        }

        $data['id'] = Db::table('app_cat')->insertGetId($data);

        if (!$data['id'])
        {
            return json(['code' => 10504, 'msg' => 'Network error.']);
        }
        return json(['code' => 200, 'data' => $data, 'msg' => 'Success.']);
    }

    /**
     * 编辑档案袋
     */
    public function edit()
    {
        $catname = htmlspecialchars(input('name/s'));
        $avatar = htmlspecialchars(input('avatar/s'));
        $id = (input('id/d', 0));

        if (!$avatar) $avatar = 'uploads/recodecat/' . rand(1, 12) . '.png';// 默认档案袋图片随机  1-4
        $uid = $this->user['id'];
        $data = [
            'id' => $id,
            'name' => $catname,
            'avatar' => $avatar,
            'last_time' => time(),
            'uid' => $uid,
        ];
        $validate = validate('RecodeCat');

        if (!$validate->scene('edit')->check($data))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $rec = Db::table('app_cat')->where(['id' => $id, 'uid' => $uid])->find();
        if (empty($rec))
        {
            return json(['code' => 10508, 'msg' => 'This recode cat is not exist.']);
        }
        $already = Db::table('app_cat')->where(['name' => $catname, 'id' => ['neq', $id], 'uid' => $uid])->find();

        if (!empty($already) && $id)
        {
            return json(['code' => 10509, 'msg' => 'This cat name already exist.']);
        }
        if (!Db::table('app_cat')->update($data))
        {
            return json(['code' => 10510, 'msg' => 'Network error.']);
        }
        return json(['code' => 200, 'data' => $data, 'msg' => 'Success.']);
    }

    /**
     * 删除档案袋
     * 删除用户自己上传的档案袋图片
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        $id = input('id/d');

//        $system_bg = [
//            'uploads/recodecat/1.png',
//            'uploads/recodecat/2.png',
//            'uploads/recodecat/3.png',
//            'uploads/recodecat/4.png',
//            'uploads/recodecat/5.png',
//            'uploads/recodecat/6.png',
//            'uploads/recodecat/7.png',
//            'uploads/recodecat/8.png',
//            'uploads/recodecat/9.png',
//            'uploads/recodecat/10.png',
//            'uploads/recodecat/11.png',
//            'uploads/recodecat/12.png',
//        ];

        $uid = $this->user['id'];

        $validate = validate('RecodeCat');

        if (!$validate->scene('del')->check(['id' => $id, 'uid' => $uid]))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $data = Db::table('app_cat')->where(['id' => $id, 'uid' => $uid])->find();

        if (empty($data)) return json(['code' => 10514, 'msg' => 'Recode Cat is not exist.']);
//        $avatar = $data['avatar'];
        // 从阿里云删除用户上传的图片
//        if (!in_array($avatar, $system_bg)) @unlink($avatar);
        // 删除档案袋
        Db::table('wechat_backup_07_18_14_43_00.app_cat')->where(['id' => $id, 'uid' => $uid])->delete();

        $hasRecode = Db::table('app_recode')
            ->alias('r')
            ->field('r.id,r.uid,rc.cid')
            ->join('wechat_backup_07_18_14_43_00.app_recode_cat rc', 'rc.rid=r.id', 'INNER')
            ->join('wechat_backup_07_18_14_43_00.app_cat c', 'c.id=rc.cid', 'INNER')
            ->where(['r.uid' => $uid, 'rc.cid' => $id])
            ->select();
        // 删除档案袋下所有的档案 （只删除关联关系，不删除实际档案）
        if (!empty($hasRecode)) Db::table('app_recode_cat')->where(['cid' => $id])->delete();

        return json(['code' => 200, 'msg' => 'DELETE Success.']);
    }

    /**
     * 获取所有档案袋列表
     */
    public function lists()
    {
        $uid = $this->user['id'];
        $data = Db::table('app_cat')->field('id,name,status,avatar,count,uid')
            ->where(['uid' => $uid, 'status' => 0])->order('id DESC')->select();

        //判断版本号
        $rec = Util::CheckAppVersion('2.1.0');
        //准币版本
        if ($rec === '大' || $rec === '同')
        {
            $is_replace = true;
        } else
        {
            $is_replace = false;
        }

        foreach ($data as $k => $datum)
        {
            if ($is_replace)
            {
                $data[$k]['avatar'] = str_replace(array('.png', '-2-2.png'), '-2.png', $datum['avatar']);
            }
        }

        return json(['code' => 200, 'data' => $data, 'msg' => 'Success']);
    }

    /**
     * 获取档案袋中的所有档案
     */
    public function recodes()
    {
        $cid = input('cid/d');

        if (!$cid) return json(['code' => 10518, 'msg' => 'Recode Cat is not exist.']);

        $uid = $this->user['id'];

        $data = [];

        try
        {
            $data = Db::table('app_recode')
                ->alias('r')
                ->field('r.id,r.uid,rc.cid')
                ->join('app_recode_cat rc', 'rc.rid=r.id', 'INNER')
                ->join('app_cat c', 'c.id=rc.cid', 'INNER')
                ->where(['r.uid' => $uid, 'rc.cid' => $cid, 'r.status' => 1])
                ->order('id DESC')
                ->select();
        }
        catch (\Exception $e)
        {

        }


        return json(['code' => 200, 'data' => $data, 'msg' => 'Success']);
    }

    /**
     * 添加档案袋背景
     */
    public function avatar($dir = 'uploads')
    {
        return (new Avatar())->upload($dir);
    }

    /**
     * 获取档案袋背景图地址列表
     */
    public function bg_lists()
    {
        $system_bg = [
            '/uploads/recodecat/1.png',
            '/uploads/recodecat/2.png',
            '/uploads/recodecat/3.png',
            '/uploads/recodecat/4.png',
            '/uploads/recodecat/5.png',
            '/uploads/recodecat/6.png',
            '/uploads/recodecat/7.png',
            '/uploads/recodecat/8.png',
            '/uploads/recodecat/9.png',
            '/uploads/recodecat/10.png',
            '/uploads/recodecat/11.png',
            '/uploads/recodecat/12.png',
        ];
        return json(['code' => 200, 'data' => $system_bg, 'msg' => 'Success.']);
    }
}
